package com.zhejiangzhengyuan.municipal_common.utils.httpUtils;

import com.alibaba.fastjson.JSON;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * @author lin_ju
 * Create on 2019/11/25
 * */
public class HttpServerUtil {
  /**
   * 获取客户端真实ip
   *
   * @param request httpServerRequest
   * @return 返回Ip地址或127.0.0.1
   */
  public static String getClientIpAddress(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
    }
    return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
  }

  public static String getBody(HttpServletRequest request) throws IOException {
    if (isFormContentType(request)) {
      return getFormContentBody(request);
    }

    return inputStream2String(request.getInputStream());
  }

  private static String inputStream2String(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int i;
    while ((i = is.read()) != -1) {
      baos.write(i);
    }
    return baos.toString();
  }

  /**
   * 是否是x-www-form-urlencoded和multipart/form-data类型
   */
  private static boolean isFormContentType(HttpServletRequest request) {
    String contentType = request.getContentType();
    if (contentType != null) {
      try {
        MediaType mediaType = MediaType.parseMediaType(contentType);
        return MediaType.APPLICATION_FORM_URLENCODED.includes(mediaType)
            || MediaType.MULTIPART_FORM_DATA.includes(mediaType);
      } catch (IllegalArgumentException ex) {
        return false;
      }
    } else {
      return false;
    }
  }

  /**
   * x-www-form-urlencoded和multipart/form-data类型的，读取parameterMap
   */
  private static String getFormContentBody(HttpServletRequest request) {
    Map<String, String[]> parameterMap = request.getParameterMap();
    if (parameterMap.size() == 1) {
      Map.Entry<String, String[]> next = parameterMap.entrySet().iterator().next();
      if (next.getValue().length == 1 && StringUtils.isEmpty(next.getValue()[0])) {
        return next.getKey();
      }
    }
    return JSON.toJSONString(parameterMap);
  }

  public static Message resolveMessage(HttpServletRequest request) throws IOException {
    String ip = getClientIpAddress(request);
    String body = getBody(request);

    Message message = new Message();
    message.setFromIp(ip);
    message.setContent(body);
    // resloveBody(message, body);
    return message;
  }
}
